package cn.kimming.wms.web.action;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;

import cn.kimming.wms.anno.RequiredPermission;
import cn.kimming.wms.domain.JsonMsg;
import cn.kimming.wms.domain.Permission;
import cn.kimming.wms.domain.Role;
import cn.kimming.wms.domain.SystemMenu;
import cn.kimming.wms.query.QueryObject;
import cn.kimming.wms.service.IPermissionService;
import cn.kimming.wms.service.IRoleService;
import cn.kimming.wms.service.ISystemMenuService;
import lombok.Getter;

@Controller("roleAction")
@Scope("prototype")
public class RoleAction extends BaseAction{

	private static final long serialVersionUID = 26674362125140616L;

	@Autowired
	private IRoleService roleService;
	@Autowired
	private IPermissionService permissionService;
	@Autowired
	private ISystemMenuService systemMenuService;
	
	@Getter
	private Role role = new Role();
	
	@Getter
	private QueryObject qo = new QueryObject();

	@Override
	@RequiredPermission("角色列表")
	@InputConfig(methodName="input")
	public String execute() {
		try {
			ActionContext.getContext().put("objs", roleService.query(qo));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return LIST;
	}
	@RequiredPermission("角色编辑")
	public String input() {
		try {
			List<Permission> permissions = permissionService.list();
			List<SystemMenu> systemMenus = systemMenuService.list();
			if (role.getId() != null) {
				role = roleService.get(role.getId());
				permissions.removeAll(role.getPermissions());
				systemMenus.removeAll(role.getMenus());
			}
			ActionContext.getContext().put("permissions", permissions);
			ActionContext.getContext().put("systemMenus", systemMenus);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return INPUT;
	}

	@RequiredPermission("角色保存和更新")
	public String saveOrUpdate() {
		if (role.getId() != null) {
			try {
				roleService.update(role);
				addActionMessage("更新成功!");
			} catch(Exception e) {
				e.printStackTrace();
				addActionError("系统异常,更新失败!");
			}
		} else {
			try {
				roleService.save(role);
				addActionMessage("保存成功!");
			} catch(Exception e) {
				e.printStackTrace();
				addActionError("系统异常,保存失败!");
			}
		}
		return SUCCESS;
	}

	@RequiredPermission("角色删除")
	public String delete() {
		try {
			if (role.getId() != null) {
				roleService.delete(role.getId());
				putJSON(new JsonMsg(true, "删除成功"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			putJSON(new JsonMsg(false, "系统异常,删除失败!"));
		}
		return NONE;
	}
	
	public void prepareSaveOrUpdate() throws Exception {
		if (role.getId()!= null) {
			role = roleService.get(role.getId());
		}
		role.getPermissions().clear();
		role.getMenus().clear();
	}
	
}
